﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IntelligentEscalator.DAL;
using IntelligentEscalator.ElevatorWebSocket;
using IntelligentEscalator.Models;
using static IntelligentEscalator.Models.MqttDataInfo;

namespace IntelligentEscalator.BUS
{
    public class HomeBUS
    {
        public ResponseMessage GetHomeData(int areaid, int isall, List<ElevatorState> list)
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaDAL da = new ElevatorAreaDAL();
            try
            {
                AreaElevatorCount content = new AreaElevatorCount();
                List<StateStatisticsNum> stateinfo = da.GetStateInfo();

                foreach (var item in stateinfo)
                {
                    if (isall == 0)
                    {
                        List<ElevatorState> elist = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == item.elevator_moving_status && e.AreaID == areaid && e.Outofservice == 0; });
                        item.stateNum = elist.Count;
                    }
                    else
                    {
                        List<ElevatorState> elist = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == item.elevator_moving_status; });
                        item.stateNum = elist.Count;
                    }
                }
                content.stateList = stateinfo;
                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
                message.total = 1;
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = "";
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询首页设备状态";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询首页设备状态" + e.ToString());
            }
            return message;
        }

        public ResponseMessage GetAreaElevatorCount()
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaDAL da = new ElevatorAreaDAL();
            try
            {
                List<AreaElevatorCount> content = da.QueryElevatorCount();
                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
                message.total = content.Count;

            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = "";
                message.total = 0;
            }
            return message;
        }

        public ResponseMessage GetElevatorPositionXY(int areaid, int isall)
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaDAL da = new ElevatorAreaDAL();
            List<Position> content = new List<Position>();
            try
            {
                List<ElevatorPosition> list = da.QueryOptionXY(areaid, isall);
                foreach (var item in list)
                {
                    Position position = new Position();
                    position.elevatorId = item.id;
                    position.elevatorName = item.elevatorName;
                    position.elevatorNO = item.elevatorNO;
                    position.optionXY = string.Format("{0},{1}", item.optionX, item.optionY);
                    position.outofservice = item.outofservice;
                    content.Add(position);
                }

                message.errcode = 0;
                message.errmsg = "";
                message.data = content;
                message.total = 1;
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = "";
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "获取设备位置";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("获取设备位置" + e.ToString());
            }
            return message;
        }

        public ResponseMessage GetElevatorState(int areaid, int isall, List<ElevatorState> list)
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaDAL da = new ElevatorAreaDAL();
            try
            {
                AreaElevatorCount content = new AreaElevatorCount();

                if (isall == 0)
                {
                    list = list.FindAll(delegate (ElevatorState e) { return e.AreaID == areaid; });
                }
                message.errcode = 0;
                message.errmsg = "";
                message.data = list;
                message.total = list.Count;
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = "";
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "获取首页电梯状态";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("获取首页电梯状态" + e.ToString());
            }
            return message;
        }

        public ResponseMessage GetFaultCount(RepairWorkOrderInfo repairWorkOrder)
        {
            ResponseMessage message = new ResponseMessage();
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            try
            {
                List<RepairWorkOrderInfo> list = da.QueryFaultCount(repairWorkOrder);
                if (list != null)
                {
                    foreach (var item in list)
                    {
                        item.reportTime = Convert.ToDateTime(item.reportTime).ToString("yyyy-MM-dd HH:mm:ss");
                        item.preparationTime = Convert.ToDateTime(item.preparationTime).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }
                message.errcode = 0;
                message.errmsg = "";
                message.data = list;
                message.total = list.Count;
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = "";
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "获取首页故障数量";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("获取首页故障数量" + e.ToString());
            }
            return message;
        }

        public ResponseMessage UpdateFaultRead(int id)
        {
            ResponseMessage message = new ResponseMessage();
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            try
            {
                string result = da.UpdateReadState(id);
                if (result == "success")
                {
                    bool result_7 = PushPromptMessage("RefreshPrompt").Result;
                    message.errcode = 0;
                    message.errmsg = "";
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = "";
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "故障标记已读";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("故障标记已读" + e.ToString());

            }
            return message;
        }

        public static async Task<bool> PushPromptMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushPromptMessage(message);
        }


        public ResponseMessage GetHomePageData()
        {
            ResponseMessage message = new ResponseMessage();
            HomePush homePush = new HomePush();
            MqttDataDAL mqttDataDAL = new MqttDataDAL();
            List<DeviceStatusData> device_list = new List<DeviceStatusData>();
            List<FaultStatisticsData> faultStatistics_list = new List<FaultStatisticsData>();
            TodayProcessData todayProcessData = new TodayProcessData();
            string manufacturerId = string.Empty;
            string manufacturer = string.Empty;
            for (int i = 0; i < 4; i++)
            {
                DeviceStatusData deviceStatusData = new DeviceStatusData();

                if (i == 0)
                {
                    manufacturerId = "04";
                    manufacturer = "KONE";

                }
                else if (i == 1)
                {
                    manufacturerId = "01";
                    manufacturer = "Schindler";

                }
                else if (i == 2)
                {
                    manufacturerId = "02";
                    manufacturer = "TKE";

                }
                else if (i == 3)
                {
                    manufacturerId = "03";
                    manufacturer = "TOSHIBA";
                }
                List<mqttdata> mqttdata = mqttDataDAL.QueryManufactyreDeviceNum(manufacturerId, manufacturer);
                foreach (var item in mqttdata)
                {
                    deviceStatusData.manufacturer = item.manufacturer;
                    if (item.dataType == "normalTotal")
                    {
                        deviceStatusData.normal = item.dataNum;
                    }
                    if (item.dataType == "deviceTotal")
                    {
                        deviceStatusData.DeviceSum = item.dataNum;
                    }
                }
                device_list.Add(deviceStatusData);

                FaultStatisticsData faultStatisticsData = new FaultStatisticsData();
                List<mqttdata> faultStatistics_mqttdata = mqttDataDAL.QueryMqttdata("FaultStatistics", manufacturerId, manufacturer);
                foreach (var item in faultStatistics_mqttdata)
                {
                    faultStatisticsData.manufacturer = manufacturer;
                    if (item.dataType == "faultTotal")
                    {
                        faultStatisticsData.faultTotal = item.dataNum;
                    }
                    else if (item.dataType == "faultToday")
                    {
                        faultStatisticsData.faultToday = item.dataNum;
                    }
                }
                faultStatistics_list.Add(faultStatisticsData);
            }

            List<mqttdata> process_mqttdata = mqttDataDAL.QueryTodayProcess();
            foreach (var item in process_mqttdata)
            {
                if (item.dataType == "inspectionTotal")
                {
                    todayProcessData.inspection = item.dataNum;
                }
                else if (item.dataType == "maintenanceTotal")
                {
                    todayProcessData.maintenance = item.dataNum;
                }
                else if (item.dataType == "faultTotal")
                {
                    todayProcessData.fault = item.dataNum;
                }
                else if (item.dataType == "inspectionCompleted")
                {
                    todayProcessData.inspectionCompleted = item.dataNum;
                }
                else if (item.dataType == "maintenanceCompleted")
                {
                    todayProcessData.maintenanceCompleted = item.dataNum;
                }
                else if (item.dataType == "faultCompleted")
                {
                    todayProcessData.faultCompleted = item.dataNum;
                }
            }

            homePush.deviceStatusData = device_list;
            homePush.faultStatisticsDatas = faultStatistics_list;
            homePush.todayProcessData = todayProcessData;
            homePush.todayRuntimeDatas = mqttDataDAL.QueryRuntime();
            homePush.faultRecordReportslist = mqttDataDAL.QueryFaultRecordReportList();
            homePush.notifications = mqttDataDAL.QueryNotificationList();
            DeviceInfoData deviceInfoData = new DeviceInfoData();
            List<devicevalue> devicevalue = mqttDataDAL.QueryDeviceInfo();
            foreach (var item in devicevalue)
            {
                if (item.dataType == "normalTotal")
                {
                    deviceInfoData.normalTotal = item.dataNum;
                }
                else if (item.dataType == "faultTotal")
                {
                    deviceInfoData.faultTotal = item.dataNum;
                }
                else if (item.dataType == "maintenanceTotal")
                {
                    deviceInfoData.maintenanceTotal = item.dataNum;
                }
                else if (item.dataType == "offlineTotal")
                {
                    deviceInfoData.offlineTotal = item.dataNum;
                }
                else if (item.dataType == "deviceTotal")
                {
                    deviceInfoData.deviceTotal = item.dataNum;
                }
            }
            homePush.DeviceInfoData = deviceInfoData;
            message.data = homePush;
            return message;
        }

        public ResponseMessage GetKoneHomePageData()
        {
            ResponseMessage message = new ResponseMessage();
            KoneHomePush homePush = new KoneHomePush();
            MqttDataDAL mqttDataDAL = new MqttDataDAL();
            TodayProcessData todayProcessData = new TodayProcessData();
            ElevatorStateBUS mBUS = new ElevatorStateBUS();
            List<mqttdata> process_mqttdata = mqttDataDAL.QueryKoneTodayProcess();
            foreach (var item in process_mqttdata)
            {
                if (item.dataType == "inspectionTotal")
                {
                    todayProcessData.inspection = item.dataNum;
                }
                else if (item.dataType == "maintenanceTotal")
                {
                    todayProcessData.maintenance = item.dataNum;
                }
                else if (item.dataType == "faultTotal")
                {
                    todayProcessData.fault = item.dataNum;
                }
                else if (item.dataType == "inspectionCompleted")
                {
                    todayProcessData.inspectionCompleted = item.dataNum;
                }
                else if (item.dataType == "maintenanceCompleted")
                {
                    todayProcessData.maintenanceCompleted = item.dataNum;
                }
                else if (item.dataType == "faultCompleted")
                {
                    todayProcessData.faultCompleted = item.dataNum;
                }
            }
            Operation operation = new Operation();
            operation.Runs = mqttDataDAL.QueryKoneRuns();
            operation.RunTime = (int)mqttDataDAL.QueryKoneRunTime() / 3600;
            operation.FailureFrequency = mqttDataDAL.QueryTotalFault();
            homePush.operation = operation;
            homePush.todayProcessData = todayProcessData;
            homePush.faultRecordReportslist = mqttDataDAL.QueryKoneFaultReportList();
            homePush.areaDeviceNums = mqttDataDAL.QueryElevatorCount();
            DeviceInfoData deviceInfoData = new DeviceInfoData();
            homePush.stateList = mBUS.GetData();
            deviceInfoData.normalTotal = ElevatorStateBUS.KoneDeviceStatus.normalTotal;
            deviceInfoData.faultTotal = ElevatorStateBUS.KoneDeviceStatus.faultTotal;
            deviceInfoData.maintenanceTotal = ElevatorStateBUS.KoneDeviceStatus.maintenanceTotal;
            deviceInfoData.offlineTotal = ElevatorStateBUS.KoneDeviceStatus.offlineTotal;
            deviceInfoData.deviceTotal = ElevatorStateBUS.KoneDeviceStatus.deviceTotal;
            homePush.DeviceInfoData = deviceInfoData;
            message.data = homePush;
            return message;
        }

        public ResponseMessage QueryPromptData()
        {
            ResponseMessage message = new ResponseMessage();
            PromptData promptData = new PromptData();
            HomeDAL homeDAL = new HomeDAL();
            promptData.inspectannually = homeDAL.QueryEarlyWarning();
            promptData.fault = homeDAL.QueryFault();
            promptData.earlywarning = homeDAL.QueryInspectAnnually();
            message.data = promptData;
            return message;
        }

        public ResponseMessage QueryInspectAnnuallyList()
        {
            ResponseMessage message = new ResponseMessage();
            HomeDAL homeDAL = new HomeDAL();
            List<MaintainInfo> list = homeDAL.QueryInspectAnnuallyList();
            message.data = list;
            return message;
        }

        public ResponseMessage QueryFaultList()
        {
            ResponseMessage message = new ResponseMessage();
            HomeDAL homeDAL = new HomeDAL();
            List<RepairWorkOrderInfo> list = homeDAL.QueryFaultList();
            message.data = list;
            return message;
        }

        public ResponseMessage QueryEarlyWarningList()
        {
            ResponseMessage message = new ResponseMessage();
            HomeDAL homeDAL = new HomeDAL();
            List<Elevator> list = homeDAL.QueryEarlyWarningList();
            message.data = list;
            return message;
        }

        public ResponseMessage GetAreaDevice(int mainareaid)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                AreaDeviceInfoData areaDeviceInfoData = new AreaDeviceInfoData();
                ElevatorStateBUS mBUS = new ElevatorStateBUS();
                List<ElevatorState> list = mBUS.GetData();
                list = list.FindAll(delegate (ElevatorState e) { return e.mainAreaId == mainareaid; });
                areaDeviceInfoData.offlineTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 1; }).Count;
                areaDeviceInfoData.normalTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 2; }).Count;
                areaDeviceInfoData.faultTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 3; }).Count;
                areaDeviceInfoData.maintenanceTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 4; }).Count;
                message.data = areaDeviceInfoData;
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "查询区域设备数量异常";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询区域设备数量";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询区域设备数量" + ex.ToString());
            }
            return message;
        }

        public ResponseMessage UpdateAnnuallyRead(int id)
        {
            ResponseMessage message = new ResponseMessage();
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            try
            {
                string result = da.UpdateAnnuallyRead(id);
                if (result == "success")
                {
                    message.errcode = 0;
                    message.errmsg = "";
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = "";
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "年检提醒标记已读";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("年检提醒标记已读" + e.ToString());
            }
            return message;
        }

        public ResponseMessage UpdateElevatorRead(int id)
        {
            ResponseMessage message = new ResponseMessage();
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            try
            {
                string result = da.UpdateElevatorRead(id);
                if (result == "success")
                {
                    message.errcode = 0;
                    message.errmsg = "";
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = "";
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "折弯次数预警标记已读";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("折弯次数预警标记已读" + e.ToString());
            }
            return message;
        }

        public ResponseMessage GetWSUrl()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                message.data = AppSettingsHelper.Configuration["WebSocketUrl"];
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "获取WebSocket地址异常";
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "获取WebSocket地址异常";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("获取WebSocket地址异常" + ex.ToString());
            }
            return message;
        }

        public ResponseMessage UpdateAllElevatorRead()
        {
            ResponseMessage message = new ResponseMessage();
            RepairWorkOrderDAL da = new RepairWorkOrderDAL();
            try
            {
                string result = da.UpdateAllElevatorRead();
                if (result == "success")
                {
                    message.errcode = 0;
                    message.errmsg = "";
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = result;
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = e.ToString();
                message.data = "";
                message.total = 0;
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "折弯次数预警标记已读";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("折弯次数预警标记已读" + e.ToString());
            }
            return message;
        }
    }
}

